#!/bin/bash
# joycon_fix_all.sh - Joy-Con手柄识别一键修复

echo "🎮 Joy-Con手柄识别一键修复工具"
echo "=================================="

# 1. 检查并安装必要软件包
echo "步骤1: 安装必要软件包..."
sudo apt update
sudo apt install -y git cmake libevdev-dev libudev-dev build-essential bluetooth bluez

# 2. 安装joycond
if ! systemctl is-active --quiet joycond; then
    echo "步骤2: 安装joycond守护进程..."
    cd /tmp
    
    if [ -d "joycond" ]; then
        rm -rf joycond
    fi
    
    git clone https://github.com/DanielOgorchock/joycond.git
    cd joycond
    cmake .
    make -j$(nproc)
    sudo make install
    
    # 启用服务
    sudo systemctl daemon-reload
    sudo systemctl enable joycond
    sudo systemctl start joycond
else
    echo "步骤2: joycond已经运行中 ✓"
fi

# 3. 加载必要的内核模块
echo "步骤3: 加载内核模块..."
sudo modprobe hid-nintendo || echo "hid-nintendo模块加载失败，可能需要更新内核"
sudo modprobe joydev

# 4. 设置用户权限
echo "步骤4: 设置用户权限..."
sudo usermod -a -G input $USER

# 5. 重启蓝牙服务
echo "步骤5: 重启蓝牙服务..."
sudo systemctl restart bluetooth

# 6. 检查服务状态
echo "步骤6: 检查服务状态..."
echo "蓝牙服务: $(systemctl is-active bluetooth)"
echo "joycond服务: $(systemctl is-active joycond)"

echo -e "\n✅ 修复完成！"
echo "请重新连接你的Joy-Con设备，然后运行检测程序"
echo "注意: 可能需要重新登录以使权限生效"
